import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_comment_list_state.dart';
import 'package:casdon/modules/lifeCircle/ui/screen/reply_list_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class LifeTopicCommentItem extends StatelessWidget {
  final String avatarUrl;
  final String userName;
  final String commentId;
  final String userId;
  final String commentTime;
  final String content;
  final int likeCount;
  final bool isLiked;
  final List<LifeTopicCommentViewData> replies;
  final String replySummary;
  final bool showDelete;
  final VoidCallback? onDeleteTap;
  final VoidCallback? onLikeTap;
  final VoidCallback? onReplyTap;

  const LifeTopicCommentItem({
    super.key,
    required this.avatarUrl,
    required this.userName,
    required this.commentId,
    required this.userId,
    required this.commentTime,
    required this.content,
    required this.likeCount,
    required this.isLiked,
    required this.replies,
    required this.replySummary,
    this.showDelete = false,
    this.onDeleteTap,
    this.onLikeTap,
    this.onReplyTap,
  });

  @override
  Widget build(BuildContext context) {
    final customColors = context.customColorThemeNonNull;
    final avatar = (avatarUrl.isEmpty || avatarUrl.isUrl() == false)
        ? AssetImage(Assets.images.icAvatar.path)
        : NetworkImage(avatarUrl) as ImageProvider;

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color: customColors.gray1 ?? Colors.grey.shade200,
            width: 1,
          ),
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(radius: 20.w, backgroundImage: avatar),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            userName,
                            style: context.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w600,
                              color: customColors.textColor1,
                            ),
                          ),
                          SizedBox(height: 4.h),
                          Text(
                            commentTime,
                            style: context.textTheme.bodySmall?.copyWith(
                              color: customColors.textColor2,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        InkWell(
                          onTap: onLikeTap,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(
                                isLiked
                                    ? Assets.images.icZaned.path
                                    : Assets.images.icZan.path,
                                width: 18.w,
                                height: 18.w,
                              ),
                              SizedBox(width: 4.w),
                              Text(
                                likeCount.toString(),
                                style: context.textTheme.bodySmall?.copyWith(
                                  color: customColors.textColor2,
                                ),
                              ),
                            ],
                          ),
                        ),
                        if (showDelete) ...[
                          SizedBox(width: 12.w),
                          InkWell(
                            onTap: onDeleteTap,
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Image.asset(
                                  Assets.images.icDel.path,
                                  width: 18.w,
                                  height: 18.w,
                                ),
                                SizedBox(width: 4.w),
                              ],
                            ),
                          ),
                        ],
                      ],
                    ),
                  ],
                ),
                SizedBox(height: 8.h),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: onReplyTap,
                  child: Text(
                    content,
                    style: context.textTheme.bodyMedium?.copyWith(
                      color: customColors.textColor1,
                      height: 1.4,
                    ),
                  ),
                ),
                if (replies.isNotEmpty) ...[
                  SizedBox(height: 12.h),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      ReplyListRoute(
                        commentId: commentId,
                        rootUserName: userName,
                        rootUserId: userId,
                      ).push(context);
                    },
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(12.w),
                      decoration: BoxDecoration(
                        color: customColors.gray1,
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _ReplyList(
                            replies: replies,
                            maxDepth: 3,
                            currentDepth: 1,
                            parentUserName: userName,
                            indent: 0,
                          ),
                          if (replySummary.isNotEmpty) ...[
                            SizedBox(height: 8.h),
                            Text(
                              replySummary,
                              style: context.textTheme.bodySmall?.copyWith(
                                color: context.colorScheme.primary,
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _ReplyList extends StatelessWidget {
  final List<LifeTopicCommentViewData> replies;
  final int maxDepth;
  final int currentDepth;
  final String parentUserName;
  final double indent;

  const _ReplyList({
    required this.replies,
    required this.maxDepth,
    required this.currentDepth,
    required this.parentUserName,
    required this.indent,
  });

  @override
  Widget build(BuildContext context) {
    final customColors = context.customColorThemeNonNull;
    const maxLines = 5;
    int remaining = maxLines;
    final List<Widget> children = [];

    void addReplies(
      List<LifeTopicCommentViewData> list,
      int depth,
      String parent,
    ) {
      if (remaining <= 0) return;
      final hasMoreDepth = depth < maxDepth;
      final nextDepth = depth + 1;

      for (final reply in list) {
        if (remaining <= 0) break;

        String baseText;
        if (depth == 1) {
          baseText = '${reply.userName}：${reply.content}';
        } else if (depth == 2) {
          baseText = '${reply.userName}：${reply.content}';
        } else {
          baseText = '${reply.userName}: 回复 @$parent：${reply.content}';
        }

        children.add(
          Padding(
            padding: EdgeInsets.only(bottom: 8.h, left: indent),
            child: Text(
              baseText,
              style: context.textTheme.bodySmall?.copyWith(
                color: customColors.textColor2,
                height: 1.4,
              ),
            ),
          ),
        );

        remaining--;

        if (remaining > 0 && hasMoreDepth && reply.replies.isNotEmpty) {
          addReplies(reply.replies, nextDepth, reply.userName);
        }
      }
    }

    addReplies(replies, currentDepth, parentUserName);

    if (children.isNotEmpty) {
      // remove bottom padding from last item
      final last = children.removeLast();
      children.add(
        Padding(
          padding: EdgeInsets.only(bottom: 0, left: indent),
          child: last,
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
  }
}
